package com.hmall.serch.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmall.common.dto.PageDTO;
import com.hmall.serch.pojo.Item;
import com.hmall.serch.pojo.ItemDoc;
import com.hmall.serch.pojo.RequestParams;
import com.hmall.serch.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Slf4j
@RequestMapping("/search")
@RestController
public class SearchControlle {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ISearchService searchService;

    @PostMapping("/list")
    public PageDTO<ItemDoc> listall(@RequestBody RequestParams requestParams) {
        log.info("对象：{}", requestParams);
        PageDTO<ItemDoc> search = searchService.search(requestParams);
        return search;
    }

    @RabbitListener(queues = "itenQueue")
    public void addAndDelect(String item) throws IOException {
        Item item1 = JSON.parseObject(item, Item.class);
        Long id = item1.getId();
        String s = id.toString();
        ItemDoc itemDoc = new ItemDoc();
        if (item1.getStatus()==1){
            BeanUtils.copyProperties(item1,itemDoc);
            String jsonString = JSON.toJSONString(itemDoc);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            // 2.准备Json文档
            request.source(jsonString, XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        }if (item1.getStatus()==2){
            DeleteRequest request = new DeleteRequest("item",s);
            client.delete(request, RequestOptions.DEFAULT);
        }
    }
}
